package excel

import (
	"github.com/xuri/excelize/v2"
)

// excel 导出
type DocumentExport struct {
	Document
}

// 创建导出
func NewExport() *DocumentExport {
	doc := DocumentExport{}
	doc.file = excelize.NewFile()

	return &doc
}

// 创建工作表
func (document *DocumentExport) NewSheet(name string) (*Sheet, error) {
	index, e := document.file.NewSheet(name)
	if e != nil {
		return nil, e
	}

	// new sheet
	v := &Sheet{}
	v.index = index
	v.name = name
	v.col = 1
	v.row = 1

	return v, e
}

// 创建流式工作表
func (document *DocumentExport) NewStreamSheet(name string) (*SheetStream, error) {
	// 创建工作表
	index, e := document.file.NewSheet(name)
	if e != nil {
		return nil, e
	}

	// 创建流式写入器
	streamWrite, e := document.file.NewStreamWriter(name)
	if e != nil {
		return nil, e
	}

	// new SheetStream
	v := &SheetStream{Sheet: &Sheet{}}
	v.w = streamWrite
	v.index = index
	v.name = name
	v.col = 1
	v.row = 1

	return v, e
}

// 创建流式工作表(函数式)
func (document *DocumentExport) NewStreamSheetFunc(name string, fn func(Sheet *SheetStream)) error {
	sw, e := document.NewStreamSheet(name)
	if e != nil {
		return e
	}

	fn(sw)

	return sw.EndPush()
}

// 创建字典Sheet(不可见)
func (document *DocumentExport) NewDictSheet(name string, values []any) error {
	_, e := document.file.NewSheet(name)
	if e != nil {
		return e
	}

	for index, v := range values {
		cellName, _ := excelize.CoordinatesToCellName(1, index+1)
		document.file.SetCellValue(name, cellName, v)
	}

	return nil
}
